from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from django.shortcuts import get_object_or_404
from .models import Article, Category, Tag
from .serializers import ArticleSerializer, CategorySerializer, TagSerializer


# 文章列表和创建
class ArticleList(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get(self, request):
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True, context={'request': request})
        return Response(serializer.data)

    def post(self, request):
        serializer = ArticleSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save(author=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 文章详情、更新、删除（id + slug）
class ArticleDetail(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_object(self, id):
        return get_object_or_404(Article, id=id)

    def get(self, request, id, slug):
        article = self.get_object(id)
        if article.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = ArticleSerializer(article, context={'request': request})
        return Response(serializer.data)

    def put(self, request, id, slug):
        article = self.get_object(id)
        if article.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        serializer = ArticleSerializer(article, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, id, slug):
        article = self.get_object(id)
        if article.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# 分类列表和创建
class CategoryList(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get(self, request):
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = CategorySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 分类详情、更新、删除（id + slug）
class CategoryDetail(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_object(self, id):
        return get_object_or_404(Category, id=id)

    def get(self, request, id, slug):
        category = self.get_object(id)
        if category.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取该分类下公开已发布的文章
        articles = Article.objects.filter(
            category=category,
            is_public=True,
            status=Article.ArticleStatus.PUBLISHED
        )
        serializer = ArticleSerializer(articles, many=True, context={'request': request})
        return Response(serializer.data)

    def put(self, request, id, slug):
        category = self.get_object(id)
        if category.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        serializer = CategorySerializer(category, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, id, slug):
        category = self.get_object(id)
        if category.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        category.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# 标签列表和创建
class TagList(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get(self, request):
        tags = Tag.objects.all()
        serializer = TagSerializer(tags, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = TagSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 标签详情、更新、删除（id + slug）
class TagDetail(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_object(self, id):
        return get_object_or_404(Tag, id=id)

    def get(self, request, id, slug):
        tags = self.get_object(id)
        if tags.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取该分类下公开已发布的文章
        articles = Article.objects.filter(
            tags=tags,
            is_public=True,
            status=Article.ArticleStatus.PUBLISHED
        )
        serializer = ArticleSerializer(articles, many=True, context={'request': request})
        return Response(serializer.data)

    def put(self, request, id, slug):
        tag = self.get_object(id)
        if tag.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        serializer = TagSerializer(tag, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, id, slug):
        tag = self.get_object(id)
        if tag.slug != slug:
            return Response({'detail': 'Slug 不匹配'}, status=status.HTTP_400_BAD_REQUEST)

        tag.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
